import { useState, useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { 
  Card, Table, Button, Input, Select, Space, Tag, message, Avatar, Form, Modal, Switch
} from 'antd'
import { 
  SearchOutlined, ReloadOutlined, UserOutlined, PhoneOutlined, MailOutlined, EditOutlined, PlusOutlined, KeyOutlined
} from '@ant-design/icons'
import { fetchAdminList } from '@/store/slices/adminSlice'
import './index.scss'

const AdminManagement = () => {
  const dispatch = useDispatch()
  const { adminList, total, loading } = useSelector((state) => state.admin)
  const { userInfo } = useSelector((state) => state.user || {})
  
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  
  // 判断是否是超级管理员
  const isSuperAdmin = userInfo?.roles?.includes('超级管理员')
  
  // 搜索表单状态
  const [searchForm, setSearchForm] = useState({
    username: '',
    nickname: '',
    status: null
  })

  // 模态框状态
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [modalType, setModalType] = useState('add') // 'add' | 'edit'
  const [currentAdmin, setCurrentAdmin] = useState(null)
  const [form] = Form.useForm()

  // 加载管理员列表
  useEffect(() => {
    dispatch(fetchAdminList({ 
      page, 
      size: pageSize
    }))
  }, [dispatch, page, pageSize])

  // 搜索
  const handleSearch = () => {
    setPage(1)
    dispatch(fetchAdminList({ 
      page: 1, 
      size: pageSize,
      ...searchForm 
    }))
  }

  // 重置
  const handleReset = () => {
    setSearchForm({
      username: '',
      nickname: '',
      status: null
    })
    setPage(1)
    dispatch(fetchAdminList({ page: 1, size: pageSize }))
  }

  // 打开模态框
  const handleOpenModal = (type, admin = null) => {
    setModalType(type)
    setCurrentAdmin(admin)
    setIsModalVisible(true)
    
    if (type === 'edit' && admin) {
      form.setFieldsValue({
        username: admin.username,
        nickname: admin.nickname,
        email: admin.email,
        phone: admin.phone,
        status: admin.status
      })
    } else {
      form.resetFields()
    }
  }

  // 关闭模态框
  const handleCloseModal = () => {
    setIsModalVisible(false)
    setCurrentAdmin(null)
    form.resetFields()
  }

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields()
      
      if (modalType === 'add') {
        // TODO: 调用添加管理员接口
        message.success('添加成功')
      } else {
        // TODO: 调用编辑管理员接口
        message.success('编辑成功')
      }
      
      handleCloseModal()
      dispatch(fetchAdminList({ page, size: pageSize }))
    } catch (error) {
      // 表单验证失败，Ant Design会自动显示错误提示
    }
  }

  // 重置密码
  const handleResetPassword = async (id) => {
    try {
      // TODO: 调用重置密码接口
      message.success('密码已重置为默认密码')
    } catch (error) {
      message.error('重置密码失败')
    }
  }

  // 切换状态
  const handleToggleStatus = async (record, checked) => {
    // 权限检查
    if (!isSuperAdmin) {
      message.warning('只有超级管理员才能操作')
      return
    }
    
    if (record.id === userInfo?.id) {
      message.warning('不能禁用自己的账号')
      return
    }
    
    try {
      const newStatus = checked ? 1 : 0
      // TODO: 调用更新状态接口
      message.success(`已${checked ? '启用' : '禁用'}该管理员`)
      dispatch(fetchAdminList({ page, size: pageSize }))
    } catch (error) {
      message.error('状态更新失败')
    }
  }


  // 表格列配置
  const columns = [
    {
      title: '管理员信息',
      key: 'adminInfo',
      width: 250,
      render: (_, record) => (
        <Space>
          <Avatar 
            src={record.avatar} 
            icon={<UserOutlined />}
            size={40}
          />
          <div>
            <div style={{ fontWeight: 'bold' }}>{record.nickname || record.username}</div>
            <div style={{ color: '#999', fontSize: '12px' }}>{record.username}</div>
          </div>
        </Space>
      )
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 130,
      render: (phone) => phone ? (
        <span>
          <PhoneOutlined style={{ color: '#1890ff', marginRight: 4 }} />
          {phone}
        </span>
      ) : <span style={{ color: '#ccc' }}>未绑定</span>
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 180,
      render: (email) => email ? (
        <span>
          <MailOutlined style={{ color: '#52c41a', marginRight: 4 }} />
          {email}
        </span>
      ) : <span style={{ color: '#ccc' }}>未绑定</span>
    },
    {
      title: '角色',
      dataIndex: 'roles',
      key: 'roles',
      width: 200,
      render: (roles) => (
        <Space wrap>
          {roles && roles.length > 0 ? (
            roles.map((role, index) => (
              <Tag color="blue" key={index}>{role}</Tag>
            ))
          ) : (
            <span style={{ color: '#ccc' }}>未分配</span>
          )}
        </Space>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 160,
      render: (time) => {
        if (!time) return '-'
        try {
          return new Date(time).toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
          })
        } catch (e) {
          return time
        }
      }
    },
    {
      title: '最后登录',
      dataIndex: 'lastLoginTime',
      key: 'lastLoginTime',
      width: 160,
      render: (time) => {
        if (!time) return '-'
        try {
          return new Date(time).toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
          })
        } catch (e) {
          return time
        }
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      align: 'center',
      render: (status, record) => {
        // 判断是否可以操作：必须是超级管理员，且不能操作自己
        const canOperate = isSuperAdmin && record.id !== userInfo?.id
        
        return (
          <Switch
            checked={status === 1}
            checkedChildren="启用"
            unCheckedChildren="禁用"
            disabled={!canOperate}
            onChange={(checked) => handleToggleStatus(record, checked)}
          />
        )
      }
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleOpenModal('edit', record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            icon={<KeyOutlined />}
            onClick={() => handleResetPassword(record.id)}
          >
            重置密码
          </Button>
        </Space>
      )
    }
  ]

  return (
    <div className="admin-management-container">
      <Card>
        {/* 搜索区域 */}
        <Form layout="inline" style={{ marginBottom: 16 }}>
          <Form.Item label="用户名" style={{ marginBottom: 8 }}>
            <Input
              placeholder="请输入用户名"
              value={searchForm.username}
              onChange={(e) => setSearchForm({ ...searchForm, username: e.target.value })}
              style={{ width: 180 }}
              allowClear
            />
          </Form.Item>
          <Form.Item label="昵称" style={{ marginBottom: 8 }}>
            <Input
              placeholder="请输入昵称"
              value={searchForm.nickname}
              onChange={(e) => setSearchForm({ ...searchForm, nickname: e.target.value })}
              style={{ width: 180 }}
              allowClear
            />
          </Form.Item>
          <Form.Item label="状态" style={{ marginBottom: 8 }}>
            <Select
              placeholder="请选择状态"
              value={searchForm.status}
              onChange={(value) => setSearchForm({ ...searchForm, status: value })}
              style={{ width: 120 }}
              allowClear
            >
              <Select.Option value={null}>全部</Select.Option>
              <Select.Option value={1}>启用</Select.Option>
              <Select.Option value={0}>禁用</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item style={{ marginBottom: 8 }}>
            <Space>
              <Button 
                type="primary" 
                icon={<SearchOutlined />}
                onClick={handleSearch}
              >
                搜索
              </Button>
              <Button 
                icon={<ReloadOutlined />}
                onClick={handleReset}
              >
                重置
              </Button>
              <Button 
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => handleOpenModal('add')}
              >
                新增管理员
              </Button>
            </Space>
          </Form.Item>
        </Form>

        {/* 统计信息 */}
        <div style={{ marginBottom: 12, color: '#666', fontSize: '14px' }}>
          共 {total} 个管理员
        </div>

        {/* 表格 */}
        <Table
          columns={columns}
          dataSource={adminList}
          loading={loading}
          rowKey="id"
          scroll={{ x: 1400, y: 600 }}
          pagination={{
            current: page,
            pageSize: pageSize,
            total: total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: (page, pageSize) => {
              setPage(page)
              setPageSize(pageSize)
            }
          }}
        />
      </Card>

      {/* 新增/编辑模态框 */}
      <Modal
        title={modalType === 'add' ? '新增管理员' : '编辑管理员'}
        open={isModalVisible}
        onOk={handleSubmit}
        onCancel={handleCloseModal}
        width={600}
        okText="确定"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          style={{ marginTop: 24 }}
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[
              { required: true, message: '请输入用户名' },
              { min: 3, max: 20, message: '用户名长度为3-20个字符' },
              { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线' }
            ]}
          >
            <Input 
              placeholder="请输入用户名" 
              disabled={modalType === 'edit'}
            />
          </Form.Item>

          {modalType === 'add' && (
            <Form.Item
              label="密码"
              name="password"
              rules={[
                { required: true, message: '请输入密码' },
                { min: 6, max: 20, message: '密码长度为6-20个字符' }
              ]}
            >
              <Input.Password placeholder="请输入密码" />
            </Form.Item>
          )}

          <Form.Item
            label="昵称"
            name="nickname"
            rules={[
              { required: true, message: '请输入昵称' },
              { max: 50, message: '昵称最多50个字符' }
            ]}
          >
            <Input placeholder="请输入昵称" />
          </Form.Item>

          <Form.Item
            label="邮箱"
            name="email"
            rules={[
              { type: 'email', message: '请输入正确的邮箱格式' }
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>

          <Form.Item
            label="手机号"
            name="phone"
            rules={[
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
            label="状态"
            name="status"
            initialValue={1}
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select>
              <Select.Option value={1}>启用</Select.Option>
              <Select.Option value={0}>禁用</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default AdminManagement
